import {
    Site,
    Coupon,
    SiteCouponConfig,
    PopupRule,
    PopupStyle,
    PopupRecord,
    PopupStats,
    SiteCouponConfigForm,
    PopupRuleForm,
    PopupStyleForm,
    SiteCouponSearchForm,
    PopupRuleSearchForm,
    PopupStyleSearchForm,
    PopupRecordSearchForm
} from '@/types/sitePopup'

// 模拟数据 - 在实际项目中这些应该从API获取
const mockSites: Site[] = [
    { id: '1', name: '煤炉', code: 'mairo', domain: 'mairo.com', status: 'active', description: '日本二手交易平台' },
    { id: '2', name: '雅虎日拍', code: 'yahoo_auction', domain: 'auctions.yahoo.co.jp', status: 'active', description: '雅虎拍卖平台' },
    { id: '3', name: '雅虎闲置', code: 'yahoo_fleamarket', domain: 'flea.yahoo.co.jp', status: 'active', description: '雅虎闲置物品平台' },
    { id: '4', name: 'Bookoff', code: 'bookoff', domain: 'bookoff.co.jp', status: 'active', description: '日本二手书店' }
]

const mockCoupons: Coupon[] = [
    { id: '1', name: '新用户专享券', type: '满减券', value: 1000, minAmount: 5000, status: 'published', validStart: '2024-01-01', validEnd: '2024-12-31', description: '新用户专享满5000减1000' },
    { id: '2', name: '全场9折券', type: '折扣券', value: 0.9, status: 'published', validStart: '2024-01-01', validEnd: '2024-12-31', description: '全场商品9折优惠' },
    { id: '3', name: '包邮券', type: '包邮券', value: 0, status: 'published', validStart: '2024-01-01', validEnd: '2024-12-31', description: '全场包邮' },
    { id: '4', name: '无门槛券', type: '无门槛券', value: 500, status: 'published', validStart: '2024-01-01', validEnd: '2024-12-31', description: '无门槛立减500日元' }
]

const mockSiteCouponConfigs: SiteCouponConfig[] = [
    {
        id: '1',
        siteId: '1',
        siteName: '煤炉',
        couponId: '1',
        couponName: '新用户专享券',
        popupRuleId: '1',
        popupRuleName: '煤炉新用户弹窗规则',
        status: 'active',
        showFrequency: 'once',
        userScope: 'new_user',
        userTags: [],
        createdAt: '2024-01-01 00:00:00',
        updatedAt: '2024-01-01 00:00:00'
    },
    {
        id: '2',
        siteId: '2',
        siteName: '雅虎日拍',
        couponId: '2',
        couponName: '全场9折券',
        popupRuleId: '2',
        popupRuleName: '雅虎日拍通用弹窗规则',
        status: 'active',
        showFrequency: 'every_visit',
        userScope: 'all',
        userTags: [],
        createdAt: '2024-01-01 00:00:00',
        updatedAt: '2024-01-01 00:00:00'
    },
    {
        id: '3',
        siteId: '3',
        siteName: '雅虎闲置',
        couponId: '3',
        couponName: '包邮券',
        popupRuleId: '3',
        popupRuleName: '新用户欢迎弹窗',
        status: 'active',
        showFrequency: 'daily',
        userScope: 'new_user',
        userTags: [],
        createdAt: '2024-01-01 00:00:00',
        updatedAt: '2024-01-01 00:00:00'
    },
    {
        id: '4',
        siteId: '4',
        siteName: 'Bookoff',
        couponId: '4',
        couponName: '无门槛券',
        popupRuleId: '4',
        popupRuleName: '通用促销弹窗',
        status: 'active',
        showFrequency: 'weekly',
        userScope: 'vip_user',
        userTags: [],
        createdAt: '2024-01-01 00:00:00',
        updatedAt: '2024-01-01 00:00:00'
    }
]

const mockPopupRules: PopupRule[] = [
    {
        id: '1',
        name: '煤炉新用户弹窗规则',
        description: '专门为煤炉平台新用户设计的欢迎弹窗，立即触发，展示新用户专享优惠信息',
        triggerType: 'immediate',
        popupTitle: '欢迎来到煤炉！',
        popupContent: '新用户专享优惠，限时领取！',
        buttonText: '立即领取',
        popupStyle: 'coupon',
        showConditions: {
            userType: 'new',
            deviceType: 'all',
            dayOfWeek: [1, 2, 3, 4, 5, 6, 7]
        },
        frequencyLimit: {
            maxShows: 1,
            period: 'session'
        },
        status: 'active',
        createdAt: '2024-01-01 00:00:00',
        updatedAt: '2024-01-01 00:00:00'
    },
    {
        id: '2',
        name: '雅虎日拍通用弹窗规则',
        description: '适用于雅虎日拍平台所有用户的通用促销弹窗，延迟3秒触发，展示全场优惠活动',
        triggerType: 'delay',
        delaySeconds: 3,
        popupTitle: '限时优惠活动',
        popupContent: '全场商品优惠，机会难得，快来选购吧！',
        buttonText: '查看详情',
        popupStyle: 'activity',
        showConditions: {
            userType: 'all',
            deviceType: 'all',
            dayOfWeek: [1, 2, 3, 4, 5, 6, 7]
        },
        frequencyLimit: {
            maxShows: 1,
            period: 'day'
        },
        status: 'active',
        createdAt: '2024-01-01 00:00:00',
        updatedAt: '2024-01-01 00:00:00'
    },
    {
        id: '3',
        name: '新用户欢迎弹窗',
        description: '适用于新用户的欢迎弹窗，延迟2秒触发，展示平台介绍和优惠信息',
        triggerType: 'delay',
        delaySeconds: 2,
        popupTitle: '欢迎来到我们的平台！',
        popupContent: '新用户专享优惠，限时领取！',
        buttonText: '立即领取',
        popupStyle: 'coupon',
        showConditions: {
            userType: 'new',
            deviceType: 'all',
            dayOfWeek: [1, 2, 3, 4, 5, 6, 7]
        },
        frequencyLimit: {
            maxShows: 1,
            period: 'session'
        },
        status: 'active',
        createdAt: '2024-01-01 00:00:00',
        updatedAt: '2024-01-01 00:00:00'
    },
    {
        id: '4',
        name: '通用促销弹窗',
        description: '适用于所有用户的促销弹窗，延迟3秒触发，展示全场优惠活动信息',
        triggerType: 'delay',
        delaySeconds: 3,
        popupTitle: '限时优惠活动',
        popupContent: '全场商品优惠，机会难得，快来选购吧！',
        buttonText: '查看详情',
        popupStyle: 'activity',
        showConditions: {
            userType: 'all',
            deviceType: 'all',
            dayOfWeek: [1, 2, 3, 4, 5, 6, 7]
        },
        frequencyLimit: {
            maxShows: 1,
            period: 'day'
        },
        status: 'active',
        createdAt: '2024-01-01 00:00:00',
        updatedAt: '2024-01-01 00:00:00'
    }
]

const mockPopupStyles: PopupStyle[] = [
    {
        id: '1',
        name: '煤炉弹窗样式',
        siteId: '1',
        siteName: '煤炉',
        position: 'center',
        width: 400,
        height: 300,
        backgroundColor: '#ffffff',
        borderColor: '#e4e7ed',
        borderWidth: 1,
        borderRadius: 8,
        shadow: true,
        animation: 'fade',
        animationDuration: 300,
        closeButton: {
            show: true,
            position: 'top_right',
            style: 'icon',
            icon: 'close'
        },
        createdAt: '2024-01-01 00:00:00',
        updatedAt: '2024-01-01 00:00:00'
    },
    {
        id: '2',
        name: '雅虎日拍弹窗样式',
        siteId: '2',
        siteName: '雅虎日拍',
        position: 'bottom_right',
        width: 350,
        height: 250,
        backgroundColor: '#f0f9ff',
        borderColor: '#3b82f6',
        borderWidth: 2,
        borderRadius: 12,
        shadow: true,
        animation: 'slide',
        animationDuration: 500,
        closeButton: {
            show: true,
            position: 'top_right',
            style: 'text',
            text: '×'
        },
        createdAt: '2024-01-01 00:00:00',
        updatedAt: '2024-01-01 00:00:00'
    }
]

const mockPopupRecords: PopupRecord[] = [
    {
        id: '1',
        siteId: '1',
        siteName: '煤炉',
        popupId: '1',
        popupName: '煤炉新用户弹窗',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        ipAddress: '192.168.1.1',
        deviceType: 'desktop',
        showTime: '2024-01-15 10:30:00',
        closeTime: '2024-01-15 10:32:00',
        action: 'close',
        createdAt: '2024-01-15 10:30:00'
    },
    {
        id: '2',
        siteId: '2',
        siteName: '雅虎日拍',
        popupId: '2',
        popupName: '雅虎日拍通用弹窗',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)',
        ipAddress: '192.168.1.2',
        deviceType: 'mobile',
        showTime: '2024-01-15 14:20:00',
        closeTime: '2024-01-15 14:25:00',
        action: 'convert',
        conversionData: {
            orderId: 'ORD001',
            amount: 15000,
            couponUsed: '全场9折券'
        },
        createdAt: '2024-01-15 14:20:00'
    }
]

const mockPopupStats: PopupStats[] = [
    {
        siteId: '1',
        siteName: '煤炉',
        totalShows: 1250,
        totalClicks: 89,
        totalConversions: 23,
        clickRate: 7.12,
        conversionRate: 1.84,
        avgShowTime: 45.6,
        revenue: 345000,
        period: '2024-01'
    },
    {
        siteId: '2',
        siteName: '雅虎日拍',
        totalShows: 2100,
        totalClicks: 156,
        totalConversions: 45,
        clickRate: 7.43,
        conversionRate: 2.14,
        avgShowTime: 52.3,
        revenue: 678000,
        period: '2024-01'
    }
]

// 站点弹窗管理服务
export class SitePopupService {
    // 获取站点列表
    static async getSites(): Promise<Site[]> {
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 300))
        return mockSites
    }

    // 获取优惠券列表
    static async getCoupons(): Promise<Coupon[]> {
        await new Promise(resolve => setTimeout(resolve, 300))
        return mockCoupons
    }

    // 获取站点优惠券配置列表
    static async getSiteCouponConfigs(params?: SiteCouponSearchForm): Promise<{ data: SiteCouponConfig[], total: number }> {
        await new Promise(resolve => setTimeout(resolve, 300))

        let filteredData = [...mockSiteCouponConfigs]

        if (params) {
            if (params.siteId) {
                filteredData = filteredData.filter(item => item.siteId === params.siteId)
            }
            if (params.status) {
                filteredData = filteredData.filter(item => item.status === params.status)
            }

        }

        return {
            data: filteredData,
            total: filteredData.length
        }
    }

    // 创建站点优惠券配置
    static async createSiteCouponConfig(config: SiteCouponConfigForm): Promise<SiteCouponConfig> {
        await new Promise(resolve => setTimeout(resolve, 500))

        const site = mockSites.find(s => s.id === config.siteId)
        const coupon = mockCoupons.find(c => c.id === config.couponId)

        if (!site || !coupon) {
            throw new Error('站点或优惠券不存在')
        }

        const newConfig: SiteCouponConfig = {
            id: Date.now().toString(),
            siteId: config.siteId,
            siteName: site.name,
            couponId: config.couponId,
            couponName: coupon.name,
            status: config.status,
            showFrequency: config.showFrequency,
            userScope: config.userScope,
            userTags: config.userTags || [],
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        }

        mockSiteCouponConfigs.push(newConfig)
        return newConfig
    }

    // 更新站点优惠券配置
    static async updateSiteCouponConfig(id: string, config: Partial<SiteCouponConfigForm>): Promise<SiteCouponConfig> {
        await new Promise(resolve => setTimeout(resolve, 500))

        const index = mockSiteCouponConfigs.findIndex(item => item.id === id)
        if (index === -1) {
            throw new Error('配置不存在')
        }

        const updatedConfig = { ...mockSiteCouponConfigs[index], ...config, updatedAt: new Date().toISOString() }
        mockSiteCouponConfigs[index] = updatedConfig

        return updatedConfig
    }

    // 删除站点优惠券配置
    static async deleteSiteCouponConfig(id: string): Promise<boolean> {
        await new Promise(resolve => setTimeout(resolve, 300))

        const index = mockSiteCouponConfigs.findIndex(item => item.id === id)
        if (index === -1) {
            throw new Error('配置不存在')
        }

        mockSiteCouponConfigs.splice(index, 1)
        return true
    }

    // 获取弹窗规则列表
    static async getPopupRules(params?: PopupRuleSearchForm): Promise<{ data: PopupRule[], total: number }> {
        await new Promise(resolve => setTimeout(resolve, 300))

        let filteredData = [...mockPopupRules]

        if (params) {
            if (params.triggerType) {
                filteredData = filteredData.filter(item => item.triggerType === params.triggerType)
            }
            if (params.status) {
                filteredData = filteredData.filter(item => item.status === params.status)
            }
        }

        return {
            data: filteredData,
            total: filteredData.length
        }
    }

    // 创建弹窗规则
    static async createPopupRule(rule: PopupRuleForm): Promise<PopupRule> {
        await new Promise(resolve => setTimeout(resolve, 500))

        const newRule: PopupRule = {
            id: Date.now().toString(),
            name: rule.name,
            description: rule.description,
            triggerType: rule.triggerType,
            delaySeconds: rule.delaySeconds,
            popupTitle: rule.popupTitle,
            popupContent: rule.popupContent,
            buttonText: rule.buttonText,
            popupStyle: rule.popupStyle,
            showConditions: rule.showConditions,
            frequencyLimit: rule.frequencyLimit,
            status: rule.status,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        }

        mockPopupRules.push(newRule)
        return newRule
    }

    // 更新弹窗规则
    static async updatePopupRule(id: string, rule: Partial<PopupRuleForm>): Promise<PopupRule> {
        await new Promise(resolve => setTimeout(resolve, 500))

        const index = mockPopupRules.findIndex(item => item.id === id)
        if (index === -1) {
            throw new Error('规则不存在')
        }

        const updatedRule = { ...mockPopupRules[index], ...rule, updatedAt: new Date().toISOString() }
        mockPopupRules[index] = updatedRule

        return updatedRule
    }

    // 删除弹窗规则
    static async deletePopupRule(id: string): Promise<boolean> {
        await new Promise(resolve => setTimeout(resolve, 300))

        const index = mockPopupRules.findIndex(item => item.id === id)
        if (index === -1) {
            throw new Error('规则不存在')
        }

        mockPopupRules.splice(index, 1)
        return true
    }

    // 获取弹窗样式列表
    static async getPopupStyles(params?: PopupStyleSearchForm): Promise<{ data: PopupStyle[], total: number }> {
        await new Promise(resolve => setTimeout(resolve, 300))

        let filteredData = [...mockPopupStyles]

        if (params) {
            if (params.siteId) {
                filteredData = filteredData.filter(item => item.siteId === params.siteId)
            }
            if (params.position) {
                filteredData = filteredData.filter(item => item.position === params.position)
            }
            if (params.animation) {
                filteredData = filteredData.filter(item => item.animation === params.animation)
            }
        }

        return {
            data: filteredData,
            total: filteredData.length
        }
    }

    // 创建弹窗样式
    static async createPopupStyle(style: PopupStyleForm): Promise<PopupStyle> {
        await new Promise(resolve => setTimeout(resolve, 500))

        const site = mockSites.find(s => s.id === style.siteId)

        if (!site) {
            throw new Error('站点不存在')
        }

        const newStyle: PopupStyle = {
            id: Date.now().toString(),
            name: style.name,
            siteId: style.siteId,
            siteName: site.name,
            position: style.position,
            width: style.width,
            height: style.height,
            backgroundColor: style.backgroundColor,
            borderColor: style.borderColor,
            borderWidth: style.borderWidth,
            borderRadius: style.borderRadius,
            shadow: style.shadow,
            animation: style.animation,
            animationDuration: style.animationDuration,
            closeButton: style.closeButton,
            customCSS: style.customCSS,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        }

        mockPopupStyles.push(newStyle)
        return newStyle
    }

    // 更新弹窗样式
    static async updatePopupStyle(id: string, style: Partial<PopupStyleForm>): Promise<PopupStyle> {
        await new Promise(resolve => setTimeout(resolve, 500))

        const index = mockPopupStyles.findIndex(item => item.id === id)
        if (index === -1) {
            throw new Error('样式不存在')
        }

        const updatedStyle = { ...mockPopupStyles[index], ...style, updatedAt: new Date().toISOString() }
        mockPopupStyles[index] = updatedStyle

        return updatedStyle
    }

    // 删除弹窗样式
    static async deletePopupStyle(id: string): Promise<boolean> {
        await new Promise(resolve => setTimeout(resolve, 300))

        const index = mockPopupStyles.findIndex(item => item.id === id)
        if (index === -1) {
            throw new Error('样式不存在')
        }

        mockPopupStyles.splice(index, 1)
        return true
    }

    // 获取弹窗展示记录
    static async getPopupRecords(params?: PopupRecordSearchForm): Promise<{ data: PopupRecord[], total: number }> {
        await new Promise(resolve => setTimeout(resolve, 300))

        let filteredData = [...mockPopupRecords]

        if (params) {
            if (params.siteId) {
                filteredData = filteredData.filter(item => item.siteId === params.siteId)
            }
            if (params.popupId) {
                filteredData = filteredData.filter(item => item.popupId === params.popupId)
            }
            if (params.action) {
                filteredData = filteredData.filter(item => item.action === params.action)
            }
            if (params.deviceType) {
                filteredData = filteredData.filter(item => item.deviceType === params.deviceType)
            }
        }

        return {
            data: filteredData,
            total: filteredData.length
        }
    }

    // 获取弹窗统计数据
    static async getPopupStats(period: string = '2024-01'): Promise<PopupStats[]> {
        await new Promise(resolve => setTimeout(resolve, 300))

        return mockPopupStats.filter(item => item.period === period)
    }

    // 预览弹窗效果
    static async previewPopup(siteId: string, styleId: string): Promise<string> {
        await new Promise(resolve => setTimeout(resolve, 200))

        const site = mockSites.find(s => s.id === siteId)
        const style = mockPopupStyles.find(s => s.id === styleId)

        if (!site || !style) {
            throw new Error('站点或样式不存在')
        }

        // 返回预览HTML代码
        return `
      <div class="popup-preview" style="
        position: fixed;
        ${style.position.includes('top') ? 'top: 20px;' : ''}
        ${style.position.includes('bottom') ? 'bottom: 20px;' : ''}
        ${style.position.includes('left') ? 'left: 20px;' : ''}
        ${style.position.includes('right') ? 'right: 20px;' : ''}
        ${style.position === 'center' ? 'top: 50%; left: 50%; transform: translate(-50%, -50%);' : ''}
        width: ${style.width}px;
        height: ${style.height}px;
        background-color: ${style.backgroundColor};
        border: ${style.borderWidth}px solid ${style.borderColor};
        border-radius: ${style.borderRadius}px;
        box-shadow: ${style.shadow ? '0 4px 12px rgba(0,0,0,0.15)' : 'none'};
        z-index: 9999;
        font-family: Arial, sans-serif;
      ">
        <div class="popup-header" style="
          padding: 15px;
          border-bottom: 1px solid #e4e7ed;
          display: flex;
          justify-content: space-between;
          align-items: center;
        ">
          <h3 style="margin: 0; color: #303133;">${site.name}优惠券</h3>
          ${style.closeButton.show ? `
            <button class="popup-close" style="
              background: none;
              border: none;
              font-size: 20px;
              cursor: pointer;
              color: #909399;
            ">${style.closeButton.style === 'text' ? style.closeButton.text : '×'}</button>
          ` : ''}
        </div>
        <div class="popup-content" style="
          padding: 20px;
          text-align: center;
        ">
          <p style="margin: 0 0 15px 0; color: #606266;">恭喜您获得专属优惠券！</p>
          <button style="
            background-color: #409eff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
          ">立即领取</button>
        </div>
      </div>
    `
    }
}

export default SitePopupService
